/*
 * Copyright (c) www.bugull.com
 */

package com.bugull.farm.core.balancer;

import java.util.List;

import org.apache.curator.framework.CuratorFramework;

import com.bugull.farm.core.cache.PropertiesCache;

/**
 *
 * @author Frank Wen(xbwen@hotmail.com)
 */
public class LeastConnectionBalancer implements Balancer {
    
    private CuratorFramework zkClient;
    
    public LeastConnectionBalancer(CuratorFramework zkClient){
        this.zkClient = zkClient;
    }

    @Override
    public String select(String workerType) throws Exception {
        List<String> workers = zkClient.getChildren().forPath(workerType);
        if(workers == null){
            return null;
        }
        int size = workers.size();
        if(size == 0){
            return null;
        }
        int leastConnection = 0;
        int leastNode = 0;
        for(int i=0; i<size; i++){
            byte[] data = zkClient.getData().forPath(workerType + "/" + workers.get(i));
            int connection = Integer.parseInt(new String(data, PropertiesCache.getInstance().get("charset.utf8")));
            if(connection <= 0){
                continue;
            }
            if(leastConnection == 0 || connection < leastConnection){
                leastConnection = connection;
                leastNode = i;
            }
        }
        return workers.get(leastNode);
    }

}
